package com.erhya.export.poi.verify;

import org.apache.commons.lang3.time.DateFormatUtils;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.Reader;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.math.BigDecimal;
import java.sql.Blob;
import java.sql.Clob;
import java.sql.SQLException;
import java.util.Date;

/**
 * 特殊类型的数据转换
 */
public class VerifyData {

    public static String verify(Date date, String format){
        return DateFormatUtils.format(date, format);
    }

    public static String verify(Clob clob){
        StringBuilder sb = new StringBuilder();;
        Reader reader = null;
        BufferedReader br = null;
        try {
            //使用 Clob 类的 free() 方法释放对象。
            Method freeMethod = clob.getClass().getMethod("free");
            freeMethod.invoke(clob);
            //使用 Clob 类的 getCharacterStream() 方法获取字符流。
            reader = clob.getCharacterStream();
            br = new BufferedReader(reader);
            String line;
            while ((line = br.readLine()) != null) {
                sb.append(line);
            }
        } catch (NoSuchMethodException | InvocationTargetException | SQLException | IOException |
                 IllegalAccessException e) {
            throw new RuntimeException(e);
        } finally {
            if (br != null){
                try {
                    br.close();
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
            if (reader != null){
                try {
                    reader.close();
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
        }
        return sb.toString();
    }

    public static String verify(BigDecimal bigDecimal, int scale, int round){
        return bigDecimal.setScale(scale, round).toPlainString();
    }

    public static String verify(Blob blob){
        try {
            byte[] bytes = blob.getBytes(1, (int) blob.length());
            return new String(bytes, "UTF-8");
        } catch (SQLException | UnsupportedEncodingException e) {
            throw new RuntimeException(e);
        }
    }
}
